--[[
	游戏服调度机器人接口
--]]

local skynet = require "skynet"
local cluster = require "skynet.cluster"
local filelog = require "filelog"
local base = require "base"
local filename = "fishscheduler.lua"

local gamename = "fishnode"
local router

local fishscheduler = {
    is_run = false,       --是否运行
}

function fishscheduler.change_schedule_state(newstate)
    fishscheduler.is_run = newstate
end

function fishscheduler.robotentertable(table_index, robotnum, level)
    local lv = level
    if lv > 2 then lv = 2 end
    local min = 7500 * 10^(lv - 1)
    local max = 8500 * 10^(lv - 1)
    local robotconf = {
        diamond = math.random(min, max),
        logicname = "fish",
    }
    skynet.sleep(100)
	pcall(cluster.call, "robotnode", ".router", "request_robot_enter", gamename, level, robotnum, robotconf)
end

function fishscheduler.check_alltableinfo()
    --桌子数量
	local status, result = skynet.pcall(router.get_alltableinfo)
    if status then
        if result.pub_tableinfos then    --只处理公开桌
            for table_index, tableinfo in pairs(result.pub_tableinfos) do
                -- filelog.debug("check_alltableinfo:", tableinfo.cur_player, tableinfo.robot_num)
                if tableinfo.cur_player > 0 and tableinfo.cur_player < 2 and tableinfo.robot_num == 0 then   --小于2人，加入机器人
                    fishscheduler.robotentertable(table_index, 1, tableinfo.game_type)
                end
            end
        end
    end
end

function fishscheduler.get_robot_stat()
    return fishscheduler.is_run
end

function fishscheduler.monitor()
	-- body
	skynet.fork(function()
        while true do
        	skynet.sleep(6 * 100)
            ----定时拉取游戏所有桌子信息
            if fishscheduler.is_run then
                pcall(fishscheduler.check_alltableinfo)
            end
        end
    end)
end

function fishscheduler.init(base)
    router = base
    fishscheduler.monitor()
end

-- skynet.start(function()
-- 	skynet.dispatch("lua",function(session, source, cmd, ...)
--         local f = fishcheduler[cmd]
--         if f then
--             skynet.retpack(f(...))
--         else
--             skynet.retpack()
--         end
--     end)
--     fishscheduler.monitor()
-- end)

return fishscheduler
